#!/bin/bash

# 宝塔服务器实时同步系统部署脚本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 检查是否为root用户
if [ "$(id -u)" -ne 0 ]; then
   echo -e "${RED}错误: 请使用root用户执行此脚本${NC}"
   exit 1
fi

# 安装依赖
echo -e "${YELLOW}正在安装依赖...${NC}"
yum install -y python3 python3-pip python3-devel git
pip3 install flask watchdog requests

# 创建工作目录
echo -e "${YELLOW}正在创建工作目录...${NC}"
mkdir -p /opt/bt_sync
cd /opt/bt_sync

# 生成随机API密钥
API_KEY=$(openssl rand -base64 32 | tr -d '+/=')

# 部署主服务器
deploy_master() {
    echo -e "${YELLOW}正在部署主服务器...${NC}"
    
    # 下载主服务器代码
    wget -O master_server.py https://raw.githubusercontent.com/your-repo/bt_sync/master/master_server.py
    
    # 配置文件
    cat > config.py << EOF
class Config:
    # 监控目录
    WATCH_DIRS = [
        '/www/wwwroot/',
        '/www/server/panel/vhost/nginx/',
        '/www/server/panel/config/'
    ]
    # API端口
    API_PORT = 5000
    # 认证密钥
    AUTH_KEY = '$API_KEY'
    # 指令存储文件
    COMMAND_FILE = 'sync_commands.json'
EOF
    
    # 创建systemd服务
    cat > /etc/systemd/system/bt_sync_master.service << EOF
[Unit]
Description=BT Panel Config Sync Master
After=network.target

[Service]
ExecStart=/usr/bin/python3 /opt/bt_sync/master_server.py
WorkingDirectory=/opt/bt_sync
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOF
    
    # 启动服务
    systemctl daemon-reload
    systemctl enable bt_sync_master
    systemctl start bt_sync_master
    
    echo -e "${GREEN}主服务器部署完成！${NC}"
    echo -e "${GREEN}API密钥: $API_KEY${NC}"
}

# 部署从服务器
deploy_slave() {
    echo -e "${YELLOW}正在部署从服务器...${NC}"
    
    # 输入主服务器IP和API密钥
    read -p "请输入主服务器IP: " MASTER_IP
    read -p "请输入API密钥: " AUTH_KEY
    
    # 下载从服务器代码
    wget -O slave_server.py https://raw.githubusercontent.com/your-repo/bt_sync/master/slave_server.py
    
    # 配置文件
    cat > config.py << EOF
class Config:
    # 主服务器API地址
    MASTER_API_URL = 'http://$MASTER_IP:5000/api/commands'
    # 认证密钥
    AUTH_KEY = '$AUTH_KEY'
    # 同步间隔（秒）
    SYNC_INTERVAL = 30
    # 本地目录映射
    PATH_MAPPING = {
        '/www/wwwroot/': '/www/wwwroot/',
        '/www/server/panel/vhost/nginx/': '/www/server/panel/vhost/nginx/',
        '/www/server/panel/config/': '/www/server/panel/config/'
    }
    # 执行命令后需要重启的服务
    SERVICES_TO_RESTART = {
        '/www/server/panel/vhost/nginx/': ['nginx'],
        '/www/server/panel/config/': ['bt']
    }
EOF
    
    # 创建systemd服务
    cat > /etc/systemd/system/bt_sync_slave.service << EOF
[Unit]
Description=BT Panel Config Sync Slave
After=network.target

[Service]
ExecStart=/usr/bin/python3 /opt/bt_sync/slave_server.py
WorkingDirectory=/opt/bt_sync
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOF
    
    # 设置SSH密钥认证（从服务器需要能SSH到主服务器）
    if [ ! -f ~/.ssh/id_rsa ]; then
        echo -e "${YELLOW}正在生成SSH密钥...${NC}"
        ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
    fi
    
    echo -e "${YELLOW}请将以下公钥添加到主服务器的~/.ssh/authorized_keys中:${NC}"
    cat ~/.ssh/id_rsa.pub
    
    read -p "添加完成后按Enter继续..."
    
    # 测试SSH连接
    echo -e "${YELLOW}正在测试SSH连接到主服务器...${NC}"
    ssh -o StrictHostKeyChecking=no root@$MASTER_IP "echo SSH连接成功"
    
    if [ $? -ne 0 ]; then
        echo -e "${RED}SSH连接失败，请检查密钥配置！${NC}"
        exit 1
    fi
    
    # 启动服务
    systemctl daemon-reload
    systemctl enable bt_sync_slave
    systemctl start bt_sync_slave
    
    echo -e "${GREEN}从服务器部署完成！${NC}"
}

# 主菜单
echo -e "${GREEN}宝塔服务器实时同步系统部署工具${NC}"
echo "1. 部署主服务器"
echo "2. 部署从服务器"
echo "3. 退出"

read -p "请选择操作 [1-3]: " choice

case $choice in
    1) deploy_master ;;
    2) deploy_slave ;;
    3) exit 0 ;;
    *) echo -e "${RED}无效选择${NC}" ;;
esac    